//
//  CJTimer.swift
//  CJPack
//
//  Created by chenjingwei on 2025/6/27.
//

import Foundation

public class CJTimer {
    
    private var timer: DispatchSourceTimer?
    private var loop: Bool = false
    private var queue: DispatchQueue
    
    public init(queue: DispatchQueue = .global()) {
        self.queue = queue
    }
    
    public func start(interval: TimeInterval, repeats: Bool = true, callbackOnMain: Bool = true, comple: @escaping () -> Void) {
        cancel()
        
        let deadline = DispatchTime.now() + interval
        let repeating = repeats ? interval : .infinity
        
        let timer = DispatchSource.makeTimerSource(queue: queue)
        timer.schedule(deadline: deadline, repeating: repeating)
        timer.setEventHandler {
            if callbackOnMain {
                DispatchQueue.main.async {
                    comple()
                }
            } else {
                comple()
            }
        }
        
        timer.resume()
        
        self.timer = timer
        self.loop = true
    }
    
    public func cancel() {
        if let timer = timer {
            timer.cancel()
            self.timer = nil
            loop = false
        }
    }
    
    public var isLoop: Bool {
        return loop
    }
    
    deinit {
        cancel()
    }
}
